﻿#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QJsonObject>
#include <QJsonDocument>
QObject *object;
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    object = this;
    convert2Json();
}
Widget::~Widget()
{
    delete ui;
}
void Widget::convert2Json()
{
    QJsonObject json;
    json.insert("result","success");
    QJsonDocument document;
    document.setObject(json);
    QByteArray array = document.toJson(QJsonDocument::Compact);
    convertFromJson(array);
    QString jsonStr = QString(array);
    qDebug()<<jsonStr;
}
void Widget::convertFromJson(QByteArray data)
{
    QJsonParseError jsonError;
    QJsonDocument document = QJsonDocument::fromJson(data,&jsonError);
    if(!document.isNull() && (jsonError.error == QJsonParseError::NoError))
    {
        if(document.isObject())
        {
            QJsonObject object = document.object();
            if(object.contains("result"))
            {
                QJsonValue value = object.value("result");
                if(value.isString())
                {
                    QString re = value.toString();
                    qDebug()<<"result:"<<re;
                }
            }
        }
    }
}
bool Widget::event(QEvent *event)
{
    if(event->type() == CustomerEvent::eventType())//过滤自定义的事件
    {
        CustomerEvent *customerEvent = dynamic_cast<CustomerEvent*>(event);
        qDebug() << customerEvent->geturlValueString();
        QString filepath = customerEvent->geturlValueString();
        qDebug()<<filepath;//控制设备，来处理
        QString type = customerEvent->getTypeValueString();
        qDebug()<<type;
    }
    return QWidget::event(event);
}
void onHttpAccepted(const QPointer<JQHttpServer::Session> &session)
{
    //有客户端调用接口时，会调用该函数
    QString method = session->requestMethod();//get post
    QString requestUrl = session->requestUrl();//url
    QString srcIP = session->requestSourceIp();//ip
    QString sendString = "";
    if(method=="GET")
    {
        QJsonObject json;
        json.insert("result","success");
        session->replyJsonObject(json);
    }
    CustomerEvent *customerEvent = new CustomerEvent(requestUrl,srcIP,method,sendString);
    QCoreApplication::postEvent(object, customerEvent);

}
void Widget::initializeHttpServer(int port)
{
    static JQHttpServer::TcpServerManage tcpServerManage(10);
    tcpServerManage.setHttpAcceptedCallback(std::bind(onHttpAccepted,std::placeholders::_1));
    const auto listenSucceed = tcpServerManage.listen(QHostAddress::Any,port);
    qDebug()<<"start Listen:"<<listenSucceed;
}
void Widget::on_btn_startHttpSever_clicked()
{
    initializeHttpServer(ui->lineEdit_port->text().toUInt());
}
